/**
 * 认证状态管理Hook
 */

import { useState, useEffect, useCallback } from 'react'
import { LoginRequest, LoginResponse, RegisterRequest } from '../types/api'
import { api, useApiCall, apiClient, getUserProfile } from '../api'

interface AuthState {
  isAuthenticated: boolean
  token: string | null
  userInfo: {
    userId: string
    username: string
    email?: string
    trueName?: string
    phone?: string
    avatar?: string
    isActive?: boolean
    isAdmin?: boolean
  } | null
}

const AUTH_STORAGE_KEY = 'auth-state'

/**
 * 从本地存储加载初始认证状态（同步）
 */
function getInitialAuthState(): AuthState {
  if (typeof window === 'undefined') {
    return {
      isAuthenticated: false,
      token: null,
      userInfo: null,
    }
  }

  try {
    const savedAuthState = localStorage.getItem(AUTH_STORAGE_KEY)
    if (savedAuthState) {
      const parsedState = JSON.parse(savedAuthState)
      return parsedState
    }
  } catch (error) {
    console.error('Failed to parse saved auth state:', error)
  }

  return {
    isAuthenticated: false,
    token: null,
    userInfo: null,
  }
}

/**
 * 认证Hook
 */
export function useAuth() {
  const [authState, setAuthState] = useState<AuthState>(getInitialAuthState)

  const { execute: executeLogin, isLoading: isLoggingIn, error: loginError } = useApiCall(
    api.auth.login,
    {
      showToast: true,
      onSuccess: async (data: LoginResponse) => {
        console.log('登录成功，收到数据:', data)
        // 设置API客户端的认证token
        apiClient.setAuthToken(data.token)
        console.log('已设置token到HTTP客户端:', data.token)
        
        try {
          // 获取用户详细信息
          const profileResponse = await getUserProfile()
          const userProfile = profileResponse.data
          
          const newAuthState = {
            isAuthenticated: true,
            token: data.token,
            userInfo: {
              userId: userProfile.id.toString(),
              username: userProfile.username,
              email: userProfile.email,
              trueName: userProfile.trueName,
              phone: userProfile.phone,
              avatar: userProfile.avatar,
              isActive: userProfile.isActive,
              isAdmin: userProfile.isAdmin,
            },
          }
          setAuthState(newAuthState)
          
          // 保存到本地存储
          if (typeof window !== 'undefined') {
            localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(newAuthState))
          }
          console.log('用户信息获取成功:', userProfile)
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 如果获取用户信息失败，使用基本信息
          const newAuthState = {
            isAuthenticated: true,
            token: data.token,
            userInfo: {
              userId: data.user_id.toString(),
              username: data.username,
            },
          }
          setAuthState(newAuthState)
          
          if (typeof window !== 'undefined') {
            localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(newAuthState))
          }
        }
      },
    }
  )

  const { execute: executeRegister, isLoading: isRegistering, error: registerError } = useApiCall(
    api.auth.register,
    {
      showToast: true,
    }
  )

  // 登录方法
  const login = useCallback(
    async (credentials: LoginRequest) => {
      return await executeLogin(credentials)
    },
    [executeLogin]
  )

  // 注册方法
  const register = useCallback(
    async (registerData: RegisterRequest) => {
      return await executeRegister(registerData)
    },
    [executeRegister]
  )

  // 登出方法
  const logout = useCallback(() => {
    setAuthState({
      isAuthenticated: false,
      token: null,
      userInfo: null,
    })
    // 清除API客户端的认证token
    apiClient.clearAuthToken()
    if (typeof window !== 'undefined') {
      localStorage.removeItem(AUTH_STORAGE_KEY)
    }
  }, [])

  // 初始化时恢复API客户端的token
  useEffect(() => {
    if (authState.token) {
      apiClient.setAuthToken(authState.token)
      console.log('已恢复API客户端token')
    }
  }, [authState.token]) // 监听 token 变化，确保任何状态更新都能同步到 API 客户端

  return {
    ...authState,
    login,
    register,
    logout,
    isLoggingIn,
    isRegistering,
    loginError,
    registerError,
  }
}